package net.WMisiedjan.WirelessRedstone.Listeners;

import java.util.ArrayList;
import java.util.List;

import net.WMisiedjan.WirelessRedstone.IWirelessPoint;
import net.WMisiedjan.WirelessRedstone.WireBox;
import net.WMisiedjan.WirelessRedstone.WirelessRedstone;

import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.WorldListener;

public class WorldListen extends WorldListener {
	private final WirelessRedstone plugin;

	public WorldListen(WirelessRedstone plugin) {
		this.plugin = plugin;
	}

	// Method borrowed from MinecraftMania! Credits to Afforess!
	// https://github.com/Afforess/MinecartMania/blob/master/src/com/afforess/minecartmaniacore/api/MinecartManiaCoreWorldListener.java
	public void onChunkUnload(ChunkUnloadEvent event) {
		if (!event.isCancelled()) {
			if (WirelessRedstone.config.isCancelChunkUnloads()) {
				try {
					List<IWirelessPoint> points = plugin.WireBox.getAllSigns();
					for (IWirelessPoint point : points) {
						if (Math.abs(event.getChunk().getX()
								- plugin.WireBox.getPointLocation(point)
										.getBlock().getChunk().getX()) > WirelessRedstone.config
								.getChunkUnloadRange()) {
							continue;
						}
						if (Math.abs(event.getChunk().getZ()
								- plugin.WireBox.getPointLocation(point)
										.getBlock().getChunk().getZ()) > WirelessRedstone.config
								.getChunkUnloadRange()) {
							continue;
						}

						WirelessRedstone.getLogger().finer(
								"Chunk prevented from unloading!");
						event.setCancelled(true);
						return;
					}
				} catch (Exception e) {
					return;
				}
			}
		}
	}
}
